#include "kmsinstallactivationthread.h"

KmsInstallActivationThread::KmsInstallActivationThread(QObject *parent)
{
    this->udpSocket = socketmanager::GetInstance()->get_udpSocket();
    this->tcpSocket = socketmanager::GetInstance()->get_tcpSocket();
    // this->udpSocket->bind(17070);
    // qDebug()<<"KmsInstallActivationThread 17070";
    this->timer = new QTimer(this);
    this->isStarted = false;
    this->port = 7070;
    this->broadcast_num = 0;
    this->udp_send_info = "";
    this->tcp_send_info = "";
    this->server_dns = "";


    connect(this->timer, SIGNAL(timeout()), this, SLOT(sendInfo()));
    connect(this->udpSocket, SIGNAL(readyRead()),this, SLOT(receiveudp()));
    connect(this->tcpSocket,SIGNAL(readyRead()),this, SLOT(receivetcp()));

}

//udp接收
void KmsInstallActivationThread::receiveudp()
{
    char buf[1024]={0};
    quint16 report;
    QString str,strbuf;
    QStringList strsplit;
    QStringList strlist;
    QByteArray ba;
    QString now_harddisk_id,now_system_uuid,now_interface_mac,allinfo;
    int ret;
    unsigned int out_size = 0;
    char * send_allinfo;
    char buffer[4096] = {0};
    memset(buffer, 0, sizeof(buffer));

    qint64 len = this->udpSocket->readDatagram(buf,sizeof(buf),&this->serverip,&report);
    if(len > 0)
    {
        str = QString::fromUtf8(buf);
        qDebug() << "udp recv:" << str;
        strsplit = str.split(":");
        if(strsplit.at(0) == "KY-ACTIVATE-SERIAL" && strsplit.size() == 2)
        {
            strbuf = strsplit.at(1);
            ba = strbuf.toLatin1();
            char * register_number = NULL;
            int i =0;
            register_number = kylin_activation_get_register_number_with_serial(ba.data(),&i);
            qDebug()<<"register number:"<<register_number;
            strlist.append(QString::fromLocal8Bit(register_number));
            strlist.append(QString::number(i));
            this->register_number = strlist.at(0);
            this->serial_number = strsplit.at(1);
            now_harddisk_id =QString::fromLocal8Bit(hardware_info_harddisk_id());
            now_system_uuid = QString::fromLocal8Bit(hardware_info_system_uuid());
            now_interface_mac = QString::fromLocal8Bit(hardware_info_network_interface_mac());
            allinfo = now_system_uuid + "'" + now_interface_mac + "'" + now_harddisk_id;
            ba = allinfo.toLatin1();
            send_allinfo = ba.data();
            ret = encrypt_hardware_info(send_allinfo, strlen(send_allinfo), (unsigned char*)buffer, &out_size);
            allinfo = QString::fromUtf8(buffer);

            this->timer->stop();
            if(this->udpSocket != NULL)
            {
                this->udpSocket->disconnectFromHost();
                this->udpSocket->close();
            }

            QString serviceTagStr, vendorStr, modelStr;
            char *serviceTag=kylin_activation_get_service_tag();
            char *vendor=kylin_activation_get_vendor();
            char *model=kylin_activation_get_model();
            serviceTagStr=QString::fromLocal8Bit(serviceTag);
            vendorStr=QString::fromLocal8Bit(vendor);
            modelStr=QString::fromLocal8Bit(model);

            this->tcp_send_info = "KY-ACTIVATE:" + strsplit.at(1) + ":" + this->register_number + ":" + allinfo
                    + ":"+QString::fromLocal8Bit(serviceTagStr.toLocal8Bit().toBase64())
                    + ":"+QString::fromLocal8Bit(vendorStr.toLocal8Bit().toBase64())
                    + ":"+QString::fromLocal8Bit(modelStr.toLocal8Bit().toBase64());
            free(serviceTag);
            free(vendor);
            free(model);

            protocolType=2;
            this->timer->start(4000);
        }
    }
}

//tcp发送
void KmsInstallActivationThread::sendtcp()
{
    qDebug()<<"tcp send:" << this->tcp_send_info;
//    this->tcpSocket->abort();
    this->tcpSocket->connectToHost(this->serverip,this->port);
    if(!this->tcpSocket->waitForConnected(3000))
    {
        return ;
    }
    int len=this->tcpSocket->write(this->tcp_send_info.toLatin1());
    this->tcpSocket->flush();
    qDebug()<<"tcp send length:"<<len;
}


//tcp接收
void KmsInstallActivationThread::receivetcp()
{
    QByteArray buf;
    QString recstr,strbuf;
    QStringList strsplit;
    QByteArray ba, ba_serial;

    int activation = 1;
    buf = this->tcpSocket->readAll();
    qDebug() << "tcp recv:" << QString(buf);
    if(!buf.isEmpty())
    {
        recstr = QString(buf);
        strsplit = recstr.split(":");
        if(strsplit.at(0) == "KY-ACTIVATE-KEY" && strsplit.size() == 3)
        {
            this->timer->stop();
            protocolType=1;

            strbuf = strsplit.at(2);
            ba = strbuf.toLocal8Bit();

            QByteArray base64by = ba.fromBase64(ba);
            QString base64str = QString::fromLocal8Bit(base64by);

            ba = base64str.toLocal8Bit();

            kylin_activation_set_customer(ba.data());

            strbuf = strsplit.at(1);
            ba = strbuf.toLatin1();

            ba_serial = this->serial_number.toLatin1();

            activation = kylin_activation_activate_system_with_serial(ba_serial.data(),ba.data());
            qDebug()<<"Activation result:"<<activation;
            this->tcpSocket->disconnectFromHost();
            qApp->exit(activation);
        }

    }
}

//udp发送
void KmsInstallActivationThread::sendudp()
{
    int length=0;
    this->broadcast_num += 1;
    int state = 1;
    int i =1;
    state =kylin_activation_activate_status(&i);
    if(state == 1)
    {
        qDebug()<<"The system has been activated!";
        qApp->exit(0);
        return ;
    }

//    if(-1==kylin_activation_system_os_check("/etc/LICENSE","/etc/.kyinfo"))
//    {
//        qDebug()<<"Authorization files do not match system version!";
//        qApp->exit(0);
//        return ;
//    }

    if(this->broadcast_num > 5)
    {
        this->timer->stop();
        qApp->exit(-1);
        return ;
    }

    qDebug()<<"server dns:"<<this->server_dns;
    qDebug()<<"udp send:" << this->udp_send_info;
    if(this->server_dns != "")
    {
        length = this->udpSocket->writeDatagram(this->udp_send_info.toLatin1(),this->udp_send_info.length(),QHostAddress(this->server_dns),this->port);
    }
    else
    {
        length = this->udpSocket->writeDatagram(this->udp_send_info.toLatin1(),this->udp_send_info.length(),QHostAddress::Broadcast,this->port);
    }
    qDebug()<<"udp send length:"<<length;
}

void KmsInstallActivationThread::sendInfo()
{
    if(protocolType==1)
        sendudp();
    else
        sendtcp();

}

void KmsInstallActivationThread::init_udpinfo()
{
    QString hdinfo, serial_number;
    char * register_number = NULL;
    int i =0;
    register_number = kylin_activation_get_encrypted_hardware_info(&i);
    hdinfo=QString::fromLocal8Bit(register_number);

    char *serial = NULL;
    serial = kylin_activation_get_serial_number(&i);
    serial_number=QString::fromLocal8Bit(serial);

    QSettings settings("/etc/kylin-activation/activation_conf.ini", QSettings::IniFormat);
    this->server_dns = settings.value("KMS_Activation/ServerIp").toString();

    this->udp_send_info = "KY-ACTIVATE:" + serial_number + ":" + hdinfo;
    free(register_number);
    free(serial);
}
